package cn.choujay.tlias.filter;

import cn.choujay.tlias.common.Result;
import cn.choujay.tlias.utils.JWTUtil;
import com.alibaba.fastjson2.JSON;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//必须要把LoginInterceptorAdapter类交给Bean管理才能够注入JWTUtil类 否则不行
@Slf4j
public class LoginInterceptorAdapter extends HandlerInterceptorAdapter {
    @Resource
    private JWTUtil jwtUtil=new JWTUtil();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }
        String token = request.getHeader("token");
        log.info("令牌为： token:{}", token);
        if (!StringUtils.hasLength(token)) {
            log.error("token 不存在");
            Result result = Result.error("NOT_LOGIN");
            String json = JSON.toJSONString(result);
            //响应
            response.getWriter().write(json);
            return false;
        }
        try {
            Claims claims = jwtUtil.parseJwt(token);

        } catch (Exception e) {
            log.info("解析失败");
            Result responseResult = Result.error("NOT_LOGIN");
            //把Result对象转换为JSON格式字符串 (fastjson是阿里巴巴提供的用于实现对象和json的转换工具类)
            String json = JSON.toJSONString(responseResult);
            //响应
            response.getWriter().write(json);
            return false;
        }

        //6.放行。
        log.info("令牌合法, 放行");
        return true;

    }
}
